layui.use(['form', 'layer', 'table', 'laydate', 'tree', 'viewer'], function () {

    var form = layui.form,
        //layer = parent.layer === undefined ? layui.layer : top.layer,
        layer = layui.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        tree = layui.tree,
        table = layui.table;

    var Viewer = layui.viewer;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    //var save_url = $('.save_url').val();
    var getMenus_url = $('.getMenus_url').val();


    // 日期
    laydate.render({
        elem: '.lay-date-range',
        type: 'datetime',
        range: '~', // '~' 自定义分割字符
        format: 'yyyy-MM-dd HH:mm:ss',
    });

    if ($('#dataTable').length > 0) {
        // Table 列表
        var tableIns = table.render({
            elem: '#dataTable',
            url: datalist_url,
            page: true,
            cellMinWidth: 95,
            //height : "full-100",
            limit: 10,
            limits: [10, 20, 50, 100],
            id: "tableList",
            cols: [[
                /*{type: "checkbox", fixed:"left", width:50},*/
                /*{field: 'id', title: '编号', width: 80, align: "center"},*/
                {field: 'name', title: '名称', align: "center"},
                {field: 'remark', title: '备注', minWidth: 180, align: "center"},
                {field: 'created_at', title: '创建时间', minWidth: 180, align: "center"},
                /*{
                    field: 'status', title: '禁用与启用', align: "center", templet: function (data) {
                        var html = '';
                        if (data.status == 1) {
                            html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '" checked>';
                        } else {
                            html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="' + data.id + '">';
                        }

                        return html;
                    }
                },*/
                {
                    title: '操作', fixed: "right", align: "center", minWidth: 160, templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                        return html;
                    }
                }
            ]],
            done: function (res, curr, count) {
                //
            }
        });

        // 搜索
        $(".search_btn").on("click", function () {
            var name = $('.searchBox').find('input[name=name]').val();
            var range_date = $('.searchBox').find('input[name=range_date]').val();
            if (name != '' || range_date != '') {
                table.reload("tableList", {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        name: name,
                        range_date: range_date
                    }
                });
            } else {
                layer.msg("请选择筛选条件");
            }
        });

        // 清空搜索
        $(".reset_btn").on("click", function () {
            table.reload("tableList", {
                where: {
                    name: '',
                    range_date: ''
                }
            });
        });

        $('.add_btn').on('click', function () {
            formHtml();
        });

        // 列表操作
        table.on('tool(dataTable)', function (obj) {
            var layEvent = obj.event,
                data = obj.data;
            // 删除
            if (layEvent === 'del') {
                layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                    $.ajax({
                        url: delete_url,
                        data: {"id": data.id},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg('已删除', {icon: 1, time: 1000});
                                tableIns.reload();
                                layer.close(index);
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                formHtml(data);
            }
        });

        // Form 表单
        function formHtml(data) {
            var content = add_url;

            if (data) {
                content = edit_url + '?id=' + data.id;
            }

            var index = layer.open({
                title: "角色管理",
                type: 2,
                maxmin: true,
                area: ["600px", "500px"],
                content: content,
                btn: ['确定', '取消'],
                success: function (layero, index) {
                    form.render();
                },
                yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index],
                        submit = layero.find('iframe').contents().find('.laySave');

                    var save_url = layero.find('iframe').contents().find('.save_url').val();
                    // 监听提交
                    iframeWindow.layui.form.on('submit(laySave)', function (data) {
                        // 获得选中的节点
                        var checkedData = iframeWindow.layui.tree.getChecked('roleTree');
                        if (checkedData.length <= 0) {
                            layer.msg("至少选择一项权限");
                            return false;
                        }

                        submitForm(data, save_url, table);
                    });

                    submit.trigger('click');
                }
            });
        }
    }

    if ($('#role_tree').length > 0) {
        var id = $('input[name=id]').val();
        if (id) {
            getMenus_url += '?id=' + id;
        }

        $.get(
            getMenus_url,
            function (res) {
                //console.log(res);
                var data = res;
                layui.role_tree = tree.render({
                    elem: '#role_tree',  // 绑定元素
                    id: 'roleTree', // 定义索引
                    data: data,
                    showCheckbox: true,
                    oncheck: function (obj) {
                        //console.log(obj.data); //得到当前点击的节点数据
                        //console.log(obj.checked); //得到当前节点的展开状态：open、close、normal
                        //console.log(obj.elem); //得到当前节点元素
                    }
                });
            }
        );
    }

    // 表单提交
    function submitForm(data, save_url, table) {
        if (data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }

        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function (res) {
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    layer.closeAll("iframe");
                    table.reload('tableList', {});
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    }
});
